<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="spuNumber">
        <el-input v-model="queryParams.spuNumber" placeholder="商品编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="商品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品类别" prop="categoryId">
        <el-input v-model="queryParams.categoryId" placeholder="商品类别" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:spu:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:spu:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:spu:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:spu:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="商品编码" align="center" prop="spuNumber" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品分类ID" align="center" prop="categoryId" />
      <el-table-column label="商品描述" align="center" prop="description" />
      <el-table-column label="供应商" align="center" prop="supplierId" />
      <el-table-column label="品牌ID" align="center" prop="brandId" />
      <el-table-column label="商品条形码" align="center" prop="skuNumberCode" />
      <el-table-column label="商品重量" align="center" prop="weightValue" />
      <el-table-column label="商品长度" align="center" prop="lengthValue" />
      <el-table-column label="商品宽度" align="center" prop="widthValue" />
      <el-table-column label="商品高度" align="center" prop="heightValue" />
      <el-table-column label="商品成本" align="center" prop="costValue" />
      <el-table-column label="商品价格" align="center" prop="priceValue" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:spu:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['basic:spu:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="1400px" append-to-body>
      <el-form ref="spuRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品编码" prop="spuNumber">
              <el-input v-model="form.spuNumber" placeholder="请输入商品编码" />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="商品分类ID" prop="categoryId">
              <el-input v-model="form.categoryId" placeholder="请输入商品分类ID" />
            </el-form-item>
            <el-form-item label="商品描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-input v-model="form.supplierId" placeholder="请输入供应商" />
            </el-form-item>
            <el-form-item label="品牌ID" prop="brandId">
              <el-input v-model="form.brandId" placeholder="请输入品牌ID" />
            </el-form-item>
            <el-form-item label="长度单位" prop="lengthUnit">
              <el-input v-model="form.lengthUnit" placeholder="请输入长度单位" />
            </el-form-item>
            <el-form-item label="体积单位" prop="volumeUnit">
              <el-input v-model="form.volumeUnit" placeholder="请输入体积单位" />
            </el-form-item>
            <el-form-item label="重量单位" prop="weightUnit">
              <el-input v-model="form.weightUnit" placeholder="请输入重量单位" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-divider content-position="center">规格信息</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAddTbSku">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="Delete" @click="handleDeleteTbSku">删除</el-button>
              </el-col>
            </el-row>
            <el-table :data="tbSkuList" :row-class-name="rowTbSkuIndex" @selection-change="handleTbSkuSelectionChange"
              ref="tbSku">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" align="center" prop="index" width="50" />
              <el-table-column label="规格编号" prop="snCode" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.snCode" placeholder="请输入规格编号" />
                </template>
              </el-table-column>
              <el-table-column label="规格名称" prop="snName" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.snName" placeholder="请输入规格名称" />
                </template>
              </el-table-column>
              <el-table-column label="商品单位" prop="skuUnit" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.skuUnit" placeholder="请输入商品单位" />
                </template>
              </el-table-column>
              <el-table-column label="商品条形码" prop="skuNumberCode" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.skuNumberCode" placeholder="请输入商品条形码" />
                </template>
              </el-table-column>
              <el-table-column label="商品重量" prop="weightValue" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.weightValue" placeholder="请输入商品重量" />
                </template>
              </el-table-column>
              <el-table-column label="商品长度" prop="lengthValue" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.lengthValue" placeholder="请输入商品长度" />
                </template>
              </el-table-column>
              <el-table-column label="商品宽度" prop="widthValue" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.widthValue" placeholder="请输入商品宽度" />
                </template>
              </el-table-column>
              <el-table-column label="商品高度" prop="heightValue" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.heightValue" placeholder="请输入商品高度" />
                </template>
              </el-table-column>
              <el-table-column label="商品成本" prop="costValue" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.costValue" placeholder="请输入商品成本" />
                </template>
              </el-table-column>
              <el-table-column label="商品价格" prop="priceValue" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.priceValue" placeholder="请输入商品价格" />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Spu">
import { listSpu, getSpu, delSpu, addSpu, updateSpu } from "@/api/basic/spu";

const { proxy } = getCurrentInstance();

const spuList = ref([]);
const tbSkuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbSku = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    spuNumber: null,
    name: null,
    categoryId: null,
  },
  rules: {
    spuNumber: [
      { required: true, message: "商品编码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "商品分类ID不能为空", trigger: "blur" }
    ],
    supplierId: [
      { required: true, message: "供应商不能为空", trigger: "blur" }
    ],
    brandId: [
      { required: true, message: "品牌ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// /** 查询商品列表 */
// function getList() {
//   loading.value = true;
//   listSpu(queryParams.value).then(response => {
//     spuList.value = response.rows;
//     total.value = response.total;
//     loading.value = false;
//   });
// }


/** 查询商品列表 */
function getList() {
  loading.value = true;
  listSpu(queryParams.value).then(response => {
    spuList.value = response.rows.map(spu => {
      spu.tbSkuList = response.rows.filter(item => item.id === spu.id).map(item => ({
        id: item.sku_id,
        snCode: item.sku_snCode,
        snName: item.sku_snName,
        skuUnit: item.sku_skuUnit,
        skuNumberCode: item.sku_skuNumberCode,
        weightValue: item.sku_weightValue,
        lengthValue: item.sku_lengthValue,
        widthValue: item.sku_widthValue,
        heightValue: item.sku_heightValue,
        costValue: item.sku_costValue,
        priceValue: item.sku_priceValue
      }));
      return spu;
    });
    total.value = response.total;
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    spuNumber: null,
    name: null,
    categoryId: null,
    description: null,
    supplierId: null,
    brandId: null,
    lengthUnit: null,
    volumeUnit: null,
    weightUnit: null,
    isDelete: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  tbSkuList.value = [];
  proxy.resetForm("spuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品";
}

// /** 修改按钮操作 */
// function handleUpdate(row) {
//   reset();
//   const _id = row.id || ids.value
//   getSpu(_id).then(response => {
//     form.value = response.data;
//     tbSkuList.value = response.data.tbSkuList;
//     open.value = true;
//     title.value = "修改商品";
//   });
// }

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getSpu(_id).then(response => {
    form.value = response.data;
    tbSkuList.value = response.data.tbSkuList || [];
    open.value = true;
    title.value = "修改商品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["spuRef"].validate(valid => {
    if (valid) {
      form.value.tbSkuList = tbSkuList.value;
      if (form.value.id != null) {
        updateSpu(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSpu(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商品编号为"' + _ids + '"的数据项？').then(function () {
    return delSpu(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 规格序号 */
function rowTbSkuIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 规格添加按钮操作 */
function handleAddTbSku() {
  let obj = {};
  obj.snCode = "";
  obj.snName = "";
  obj.skuUnit = "";
  obj.skuNumberCode = "";
  obj.weightValue = "";
  obj.lengthValue = "";
  obj.widthValue = "";
  obj.heightValue = "";
  obj.costValue = "";
  obj.priceValue = "";
  tbSkuList.value.push(obj);
}

/** 规格删除按钮操作 */
function handleDeleteTbSku() {
  if (checkedTbSku.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的规格数据");
  } else {
    const tbSkus = tbSkuList.value;
    const checkedTbSkus = checkedTbSku.value;
    tbSkuList.value = tbSkus.filter(function (item) {
      return checkedTbSkus.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTbSkuSelectionChange(selection) {
  checkedTbSku.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/spu/export', {
    ...queryParams.value
  }, `spu_${new Date().getTime()}.xlsx`)
}

getList();
</script>
